/**
 * @a https://leetcode.cn/problems/3sum-closest/
 */
#include "common.h"

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        int sz = nums.size();
        int min_error = INT_MAX, ret = 0;
        for(int i = 0; i < sz - 2; ++i){
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue; // 跳到for循环的下一次迭代
            }
            int left = i + 1, right = sz - 1;
            while(left < right){
                if(nums[i] + nums[left] + nums[right] == target){
                    return nums[i] + nums[left] + nums[right];
                }
                else if(nums[i] + nums[left] + nums[right] > target){
                    int error = abs(target - (nums[i] + nums[left] + nums[right]));
                    if(min_error > error)
                    {
                        min_error = error;
                        ret = nums[i] + nums[left] + nums[right];
                    }
                    right--;
                }
                else{
                    int error = abs(target - (nums[i] + nums[left] + nums[right]));
                    if(min_error > error)
                    {
                        min_error = error;
                        ret = nums[i] + nums[left] + nums[right];
                    }
                    left++;
                }
            }
        }
        return ret;
    }
};